<template>
  <div class="promotion-management">
    <h2 class="page-title">营销活动管理</h2>
    
    <!-- 操作栏 -->
    <el-card class="action-card">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-form :inline="true" :model="queryForm" class="query-form">
            <el-form-item label="活动状态">
              <el-select v-model="queryForm.status" placeholder="全部状态" clearable>
                <el-option label="全部状态" value=""></el-option>
                <el-option label="未开始" :value="0"></el-option>
                <el-option label="进行中" :value="1"></el-option>
                <el-option label="已结束" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="活动类型">
              <el-select v-model="queryForm.type" placeholder="全部类型" clearable>
                <el-option label="全部类型" value=""></el-option>
                <el-option label="满减优惠" :value="1"></el-option>
                <el-option label="折扣优惠" :value="2"></el-option>
                <el-option label="特价菜品" :value="3"></el-option>
                <el-option label="新品推广" :value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button type="success" icon="el-icon-plus" @click="openCreateDialog">创建活动</el-button>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 活动列表 -->
    <el-card class="list-card" v-loading="loading">
      <div class="promotion-list">
        <el-table :data="promotionList" border stripe style="width: 100%">
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="活动名称" width="180"></el-table-column>
          <el-table-column prop="type" label="活动类型" width="120">
            <template slot-scope="scope">
              <el-tag :type="getTypeTagType(scope.row.type)">
                {{ getTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="160"></el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="160"></el-table-column>
          <el-table-column prop="status" label="活动状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="rule" label="活动规则" min-width="200">
            <template slot-scope="scope">
              <div v-html="formatRule(scope.row)"></div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button 
                type="text" 
                size="small" 
                @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button 
                v-if="scope.row.status !== 2" 
                type="text" 
                size="small" 
                @click="handleEnd(scope.row)">结束</el-button>
              <el-button 
                type="text" 
                size="small" 
                style="color: #F56C6C;" 
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryForm.size"
          :current-page="queryForm.page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 创建/编辑活动对话框 -->
    <el-dialog
      :title="dialogType === 'create' ? '创建活动' : '编辑活动'"
      :visible.sync="dialogVisible"
      width="600px">
      <el-form :model="promotionForm" :rules="rules" ref="promotionForm" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="promotionForm.name" placeholder="请输入活动名称"></el-input>
        </el-form-item>
        
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="promotionForm.type" placeholder="请选择活动类型" style="width: 100%;">
            <el-option label="满减优惠" :value="1"></el-option>
            <el-option label="折扣优惠" :value="2"></el-option>
            <el-option label="特价菜品" :value="3"></el-option>
            <el-option label="新品推广" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="promotionForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        
        <!-- 满减优惠规则 -->
        <template v-if="promotionForm.type === 1">
          <el-form-item label="满减门槛" prop="threshold">
            <el-input-number v-model="promotionForm.threshold" :min="1" :precision="2" :step="10" controls-position="right" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="减免金额" prop="discount">
            <el-input-number v-model="promotionForm.discount" :min="0.1" :precision="2" :step="5" controls-position="right" style="width: 100%;"></el-input-number>
          </el-form-item>
        </template>
        
        <!-- 折扣优惠规则 -->
        <template v-if="promotionForm.type === 2">
          <el-form-item label="折扣比例" prop="discountRate">
            <el-input-number v-model="promotionForm.discountRate" :min="1" :max="9.9" :precision="1" :step="0.1" controls-position="right" style="width: 100%;">
              <template slot="append">折</template>
            </el-input-number>
          </el-form-item>
        </template>
        
        <!-- 特价菜品规则 -->
        <template v-if="promotionForm.type === 3">
          <el-form-item label="选择菜品" prop="foodIds">
            <el-select
              v-model="promotionForm.foodIds"
              multiple
              filterable
              placeholder="请选择特价菜品"
              style="width: 100%;">
              <el-option
                v-for="food in foodOptions"
                :key="food.id"
                :label="food.name"
                :value="food.id">
                <span style="float: left">{{ food.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">¥{{ food.price }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="特价折扣" prop="foodDiscountRate">
            <el-input-number v-model="promotionForm.foodDiscountRate" :min="1" :max="9.9" :precision="1" :step="0.1" controls-position="right" style="width: 100%;">
              <template slot="append">折</template>
            </el-input-number>
          </el-form-item>
        </template>
        
        <!-- 新品推广规则 -->
        <template v-if="promotionForm.type === 4">
          <el-form-item label="选择新品" prop="newFoodIds">
            <el-select
              v-model="promotionForm.newFoodIds"
              multiple
              filterable
              placeholder="请选择新品"
              style="width: 100%;">
              <el-option
                v-for="food in newFoodOptions"
                :key="food.id"
                :label="food.name"
                :value="food.id">
                <span style="float: left">{{ food.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">¥{{ food.price }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推广描述" prop="description">
            <el-input type="textarea" v-model="promotionForm.description" :rows="3" placeholder="请输入新品推广描述"></el-input>
          </el-form-item>
        </template>
        
        <el-form-item label="活动描述" prop="description">
          <el-input type="textarea" v-model="promotionForm.description" :rows="3" placeholder="请输入活动描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'PromotionManagement',
  data() {
    return {
      // 查询参数
      queryForm: {
        page: 1,
        size: 10,
        merchantId: null,
        status: '',
        type: ''
      },
      
      // 商家ID
      merchantId: null,
      
      // 活动列表
      promotionList: [],
      
      // 总记录数
      total: 0,
      
      // 加载状态
      loading: false,
      
      // 对话框类型（创建/编辑）
      dialogType: 'create',
      
      // 对话框可见性
      dialogVisible: false,
      
      // 活动表单
      promotionForm: {
        id: null,
        merchantId: null,
        name: '',
        type: 1,
        timeRange: [],
        startTime: '',
        endTime: '',
        status: 0,
        threshold: 50,
        discount: 10,
        discountRate: 9,
        foodIds: [],
        newFoodIds: [],
        foodDiscountRate: 8,
        description: ''
      },
      
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择活动类型', trigger: 'change' }
        ],
        timeRange: [
          { required: true, message: '请选择活动时间范围', trigger: 'change' }
        ],
        threshold: [
          { required: true, message: '请输入满减门槛', trigger: 'blur' }
        ],
        discount: [
          { required: true, message: '请输入减免金额', trigger: 'blur' }
        ],
        discountRate: [
          { required: true, message: '请输入折扣比例', trigger: 'blur' }
        ],
        foodIds: [
          { required: true, message: '请选择特价菜品', trigger: 'change' }
        ],
        foodDiscountRate: [
          { required: true, message: '请输入特价折扣', trigger: 'blur' }
        ],
        newFoodIds: [
          { required: true, message: '请选择新品', trigger: 'change' }
        ],
        description: [
          { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
        ]
      },
      
      // 菜品选项
      foodOptions: [],
      
      // 新品选项
      newFoodOptions: []
    }
  },
  created() {
    this.getMerchantId()
  },
  methods: {
    // 获取商家ID
    getMerchantId() {
      const userId = this.$store.state.user.id
      axios.get(`/api/merchants/user/${userId}`)
        .then(response => {
          if (response.code === 200) {
            this.merchantId = response.data.id
            this.queryForm.merchantId = response.data.id
            this.promotionForm.merchantId = response.data.id
            
            this.fetchPromotionList()
            this.fetchFoodOptions()
          } else {
            this.$message.error(response.message || '获取商家信息失败')
          }
        })
        .catch(error => {
          console.error('获取商家信息失败', error)
          this.$message.error('获取商家信息失败')
        })
    },
    
    // 获取活动列表
    fetchPromotionList() {
      this.loading = true
      
      axios.get(`/api/promotions/merchant/${this.merchantId}`, {
        params: {
          page: this.queryForm.page,
          size: this.queryForm.size,
          status: this.queryForm.status,
          type: this.queryForm.type
        }
      })
        .then(response => {
          if (response.code === 200) {
            this.promotionList = response.data
            this.total = response.total
          } else {
            this.$message.error(response.message || '获取活动列表失败')
          }
          this.loading = false
        })
        .catch(error => {
          console.error('获取活动列表失败', error)
          this.$message.error('获取活动列表失败')
          this.loading = false
        })
    },
    
    // 获取菜品选项
    fetchFoodOptions() {
      axios.get(`/api/foods/merchant/${this.merchantId}`, {
        params: {
          status: 1
        }
      })
        .then(response => {
          if (response.code === 200) {
            this.foodOptions = response.data || []
            
            // 最近30天内新增的菜品作为新品选项
            const thirtyDaysAgo = new Date()
            thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
            
            this.newFoodOptions = this.foodOptions.filter(food => {
              const createTime = new Date(food.createTime)
              return createTime >= thirtyDaysAgo
            })
          } else {
            this.$message.error(response.message || '获取菜品列表失败')
          }
        })
        .catch(error => {
          console.error('获取菜品列表失败', error)
          this.$message.error('获取菜品列表失败')
        })
    },
    
    // 处理搜索
    handleSearch() {
      this.queryForm.page = 1
      this.fetchPromotionList()
    },
    
    // 重置查询
    resetQuery() {
      this.queryForm = {
        page: 1,
        size: 10,
        merchantId: this.merchantId,
        status: '',
        type: ''
      }
      this.fetchPromotionList()
    },
    
    // 打开创建对话框
    openCreateDialog() {
      this.dialogType = 'create'
      this.promotionForm = {
        id: null,
        merchantId: this.merchantId,
        name: '',
        type: 1,
        timeRange: [],
        startTime: '',
        endTime: '',
        status: 0,
        threshold: 50,
        discount: 10,
        discountRate: 9,
        foodIds: [],
        newFoodIds: [],
        foodDiscountRate: 8,
        description: ''
      }
      this.dialogVisible = true
      
      // 在下一个事件循环重置表单验证
      this.$nextTick(() => {
        this.$refs.promotionForm && this.$refs.promotionForm.clearValidate()
      })
    },
    
    // 打开编辑对话框
    openEditDialog(promotion) {
      this.dialogType = 'edit'
      
      // 复制活动数据
      this.promotionForm = {
        id: promotion.id,
        merchantId: promotion.merchantId,
        name: promotion.name,
        type: promotion.type,
        timeRange: [promotion.startTime, promotion.endTime],
        startTime: promotion.startTime,
        endTime: promotion.endTime,
        status: promotion.status,
        threshold: promotion.threshold || 50,
        discount: promotion.discount || 10,
        discountRate: promotion.discountRate || 9,
        foodIds: promotion.foodIds || [],
        newFoodIds: promotion.newFoodIds || [],
        foodDiscountRate: promotion.foodDiscountRate || 8,
        description: promotion.description || ''
      }
      
      this.dialogVisible = true
      
      // 在下一个事件循环重置表单验证
      this.$nextTick(() => {
        this.$refs.promotionForm && this.$refs.promotionForm.clearValidate()
      })
    },
    
    // 提交表单
    submitForm() {
      this.$refs.promotionForm.validate((valid) => {
        if (valid) {
          // 处理时间范围
          if (this.promotionForm.timeRange && this.promotionForm.timeRange.length === 2) {
            this.promotionForm.startTime = this.promotionForm.timeRange[0]
            this.promotionForm.endTime = this.promotionForm.timeRange[1]
          }
          
          const formData = { ...this.promotionForm }
          delete formData.timeRange // 删除timeRange字段，后端不需要
          
          if (this.dialogType === 'create') {
            // 创建活动
            axios.post('/api/promotions', formData)
              .then(response => {
                if (response.code === 200) {
                  this.$message.success('创建活动成功')
                  this.dialogVisible = false
                  this.fetchPromotionList()
                } else {
                  this.$message.error(response.message || '创建活动失败')
                }
              })
              .catch(error => {
                console.error('创建活动失败', error)
                this.$message.error('创建活动失败')
              })
          } else {
            // 更新活动
            axios.put(`/api/promotions/${this.promotionForm.id}`, formData)
              .then(response => {
                if (response.code === 200) {
                  this.$message.success('更新活动成功')
                  this.dialogVisible = false
                  this.fetchPromotionList()
                } else {
                  this.$message.error(response.message || '更新活动失败')
                }
              })
              .catch(error => {
                console.error('更新活动失败', error)
                this.$message.error('更新活动失败')
              })
          }
        } else {
          return false
        }
      })
    },
    
    // 结束活动
    handleEnd(promotion) {
      this.$confirm(`确定要结束"${promotion.name}"活动吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/promotions/${promotion.id}/end`)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('活动已结束')
              this.fetchPromotionList()
            } else {
              this.$message.error(response.message || '操作失败')
            }
          })
          .catch(error => {
            console.error('结束活动失败', error)
            this.$message.error('操作失败')
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 删除活动
    handleDelete(promotion) {
      this.$confirm(`确定要删除"${promotion.name}"活动吗? 删除后无法恢复!`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        axios.delete(`/api/promotions/${promotion.id}`)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchPromotionList()
            } else {
              this.$message.error(response.message || '删除失败')
            }
          })
          .catch(error => {
            console.error('删除活动失败', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 处理每页大小变化
    handleSizeChange(size) {
      this.queryForm.size = size
      this.fetchPromotionList()
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.queryForm.page = page
      this.fetchPromotionList()
    },
    
    // 获取类型标签类型
    getTypeTagType(type) {
      const types = {
        1: 'success',
        2: 'primary',
        3: 'warning',
        4: 'info'
      }
      return types[type] || ''
    },
    
    // 获取类型文本
    getTypeText(type) {
      const texts = {
        1: '满减优惠',
        2: '折扣优惠',
        3: '特价菜品',
        4: '新品推广'
      }
      return texts[type] || '未知类型'
    },
    
    // 获取状态标签类型
    getStatusTagType(status) {
      const types = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return types[status] || ''
    },
    
    // 获取状态文本
    getStatusText(status) {
      const texts = {
        0: '未开始',
        1: '进行中',
        2: '已结束'
      }
      return texts[status] || '未知状态'
    },
    
    // 格式化活动规则
    formatRule(promotion) {
      let ruleText = ''
      
      switch (promotion.type) {
        case 1:
          ruleText = `消费满 ${promotion.threshold} 元减 ${promotion.discount} 元`
          break
        case 2:
          ruleText = `全场商品 ${promotion.discountRate} 折优惠`
          break
        case 3:
          const foodCount = promotion.foodIds ? promotion.foodIds.length : 0
          ruleText = `${foodCount} 件特价菜品，${promotion.foodDiscountRate} 折优惠`
          break
        case 4:
          const newFoodCount = promotion.newFoodIds ? promotion.newFoodIds.length : 0
          ruleText = `${newFoodCount} 件新品推广`
          break
        default:
          ruleText = '暂无规则'
      }
      
      return ruleText
    }
  }
}
</script>

<style scoped>
.promotion-management {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.action-card {
  margin-bottom: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 